import { Middleware } from "koa";
import { RuntimeError } from "../model/RuntimeErrorr";
import { Result } from "../factory/Result";
import { validateTimingData } from "../utils/validate";
import { ListTaskResultMapParam } from "../model/ListResult";
import { notEmpty } from "../utils/isEmpty";
import { BuildTaskType } from "../model/BuildTask";
import { buildTaskResultService } from "../service/BuildTaskResultService";
import { BuildTaskResult } from "../model/TaskResultDBSchema";

/**
 * 当一个任务有结果时，添加一条记录
 * @param ctx
 * @param next
 */
export const addTaskResult: Middleware = async (ctx, next) => {
  const bodyData = ctx.request.body || {};
  // 数据校验
  const { valid, data, errorMsg } = validateTimingData(bodyData);
  if (!valid) throw new RuntimeError(errorMsg);
  // 插入数据
  await buildTaskResultService.add(data);
  ctx.body = Result.success("记录添加成功");
};

export const listTaskResultMap: Middleware = async (ctx) => {
  const param: ListTaskResultMapParam = ctx.request.body || {};
  // 直接查询
  const keys = Object.keys(param);
  let rslt: BuildTaskResult[] | undefined = [];
  if (!keys.length) {
    rslt = await buildTaskResultService.list();
  } else {
    rslt = await buildTaskResultService.list((val) => {
      for (let key of keys) {
        const p = param[key as keyof ListTaskResultMapParam];
        switch (key as keyof ListTaskResultMapParam) {
          case "startDate":
          case "endDate":
            if (notEmpty(param.endDate) && notEmpty(param.startDate)) {
              return val.start >= param.startDate && val.start <= param.endDate;
            }
            break;
          case "status":
            if (notEmpty(p)) {
              return val.status === p;
            }
            break;
          case "type":
            if (notEmpty(p)) {
              if (Array.isArray(p)) {
                return p.includes(val.type);
              }
              return (p as BuildTaskType) === val.type;
            }
          case "taskId":
            if (notEmpty(p)) {
              return val.taskId === p;
            }
            break;
          default:
            break;
        }
      }
      return false;
    });
  }

  // 转为根据类型分类的对象
  const rsltMap: any = {};
  (rslt || []).map((v) => {
    if (!rsltMap[v.type]) {
      rsltMap[v.type] = [];
    }
    rsltMap[v.type].push(v);
  });
  ctx.body = Result.success(rsltMap);
};
